package org.ysling.litemall.core.satoken.handler;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.ysling.litemall.core.service.CommonService;
import org.ysling.litemall.core.utils.bcrypt.BCryptPasswordEncoder;
import org.ysling.litemall.db.domain.LitemallAdmin;
import org.ysling.litemall.db.service.IAdminService;
import java.util.List;

/**
 * 授权登陆
 * @author Ysling
 */
@Slf4j
@Component
public class AuthenticationInfo {

    private static CommonService commonService;
    public AuthenticationInfo(CommonService commonService){
        AuthenticationInfo.commonService = commonService;
    }

    /**
     * 授权登陆
     * @param token 登陆实体
     */
    public static void login(LitemallAdmin token) {
        String username = token.getUsername();
        String password = token.getPassword();
        if (!StringUtils.hasText(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new RuntimeException("密码不能为空");
        }

        List<LitemallAdmin> adminList = commonService.findAdmin(username);
        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if (adminList.size() == 0) {
            throw new RuntimeException("找不到用户（" + username + "）的帐号信息");
        }

        LitemallAdmin admin = adminList.get(0);
        if (token.getId() == null){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (!encoder.matches(password, admin.getPassword())) {
                throw new RuntimeException("账号或密码错误");
            }
        }

        //退出登陆
        StpUtil.logout(admin.getId());
        //账号登陆
        StpUtil.login(admin.getId());
        //对象拷贝
        BeanUtil.copyProperties(admin, token);
    }

}
